﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using ProjetoComperio.Framework.Configuration;

namespace ProjetoComperio.Framework.Web.Mail
{
    /// <summary>
    /// Utility class to send comperio email
    /// </summary>
    public class MailSender
    {
        /// <summary>
        /// This method send mail  with suporte@projetocomperio.org as sender
        /// </summary>
        /// <param name="messageTo"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static bool SendMail(string messageTo, string subject, string body)
        {
            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587 /* TLS */);
            smtpClient.EnableSsl = true;
            MailAddress sender = new MailAddress(ConfigurationLoader.LoadValue(ConfigurationLoader.Keys.MAILSENDERLOGIN), ConfigurationLoader.LoadValue(ConfigurationLoader.Keys.MAILSENDERPASSWORD));
            MailAddress to = new MailAddress(messageTo);

            MailMessage message = new MailMessage(sender, to);
            message.IsBodyHtml = true;
            message.Body = body;
            message.Subject = subject;
            NetworkCredential credential = new NetworkCredential(ConfigurationLoader.LoadValue(ConfigurationLoader.Keys.MAILSENDERLOGIN), ConfigurationLoader.LoadValue(ConfigurationLoader.Keys.MAILSENDERPASSWORD));
            smtpClient.Credentials = credential;
            try
            {
                smtpClient.Send(message);
            }
            catch (Exception e)
            {
                return false;
            }

            return true;
        }
    }
}
